package linkeddata.arida.ufc.br.servlet;

import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import linkeddata.arida.ufc.br.endpoints.LoadFileUrl;
import linkeddata.arida.ufc.br.endpoints.Prefix;

public class GetPropertiesServlet extends HttpServlet {

    /**
     * I have no idea why this was generated! -- Oshani
     */
    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

        String service = request.getParameter("service");
        String prefixes = request.getParameter("prefixes");
        
        LoadFileUrl load = new LoadFileUrl(prefixes);
        Prefix prefix = new Prefix(load);
        
        String responseStr = "";
        
        try {
            if (service == null) {
                // The request parameter 'param' was not present in the query string
                // e.g. http://hostname.com?a=b
            } else if ("".equals(service)) {
                // The request parameter 'param' was present in the query string but has no value
                // e.g. http://hostname.com?param=&a=b
            }

            String query = prefix.prefixes() + "SELECT DISTINCT ?p WHERE {?s ?p ?o}";

            QueryExecution qe = QueryExecutionFactory.sparqlService(service, query);
            ResultSet results = qe.execSelect();

            while (results.hasNext()) {
                QuerySolution qs = results.next();
                responseStr += qs.get("p") + ",";
            }
        } catch (Exception e) {
            System.err.println(e);
        }

        response.setContentType("text/plain");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(responseStr);
    }
}
